const { mkPager } = require('../utils')
const { nonCommitStatus } = require('./approveHelper.js')
const { findLoanByLimitNameStatusIn,
  countLoanByNameStatusIn,
  findLoanByLimitStatusIn,
  countLoanByStatusIn,
  findLoanById,
  updateLoanByfields } = require('../models/loan.js')
const { stateFlow } = require('./approveHelper')
const path = require('path')
const { fileExit } = require('../utils')
const { genContract } = require('../utils/docHelper.js')
const fs = require('fs')

exports.list = async ctx => {
  const { pageNo, pageSize, name } = ctx.query;
  const { start, size } = mkPager(pageNo, pageSize);

  if (name) {
    var loanRes = await findLoanByLimitNameStatusIn(start, size, name, ...nonCommitStatus)
    var countRes = await countLoanByNameStatusIn(name, ...nonCommitStatus)
  } else {
    var loanRes = await findLoanByLimitStatusIn(start, size, ...nonCommitStatus)
    var countRes = await countLoanByStatusIn(...nonCommitStatus)
  }

  const rows = countRes[0].rows
  const pages = Math.ceil(rows / size)

  ctx.success({
    data: {
      data: loanRes
    },
    rows,
    pages
  })
}

exports.createFile = async ctx => {
  const { id } = ctx.request.body;
  const loanRes = await findLoanById(id);
  if (loanRes.length === 0) {
    return ctx.fail('申请不存在！')
  }

  const originStatus = loanRes[0].status;
  const currentStatus = stateFlow[originStatus];
  const nextStatus = currentStatus.pass;
  if (currentStatus.v !== 5) {
    return ctx.fail(`当前状态无法生成合同，当前状态为:${currentStatus.v}`)
  }

  const info = { ...loanRes[0] }
  info['create_time'] = new Date(info['create_time']).toLocaleDateString().replace(/\//gi, '-')
  info['update_time'] = new Date(info['update_time']).toLocaleDateString().replace(/\//gi, '-')
  const filePath = path.join(__dirname, '../download', `contract-${id}.docx`)

  let fileSuccess = true;
  // 判断文件是否存在，不存在则创建
  const idExit = fileExit(filePath)
  if (!idExit) {
    // 创建word文件
    try {
      await genContract(info, filePath)
      fileSuccess = true
    } catch (error) {
      fileSuccess = false
    }
  }
  if (!fileSuccess) {
    return ctx.fail('生成合同失败！！！')
  }
  // 变更数据库状态  nextStatus.v
  const updateRes = await updateLoanByfields({ status: nextStatus.v }, id)
  if (updateRes.changedRows === 0) {
    return ctx.fail('更新失败')
  }
  ctx.success('文件创建成功！')

}

exports.downloadUrl = async ctx => {
  const { id } = ctx.query;
  const filePath = path.join(__dirname, '../download', `contract-${id}.docx`)
  // 判断文件是否存在
  const idExit = fileExit(filePath)
  if (!idExit) {
    return ctx.fail('文件不存在！')
  }

  // download/:contract-${id}.docx
  return ctx.success({
    info: 'url获取成功',
    url: `/api/contract/download/contract-${id}.docx`
  })
}

exports.downloadFile = async ctx => {
  const { filename } = ctx.params
  const filePath = path.join(__dirname, '../download', filename)
  // 判断文件是否存在
  const idExit = fileExit(filePath)
  if (!idExit) {
    return ctx.fail('文件不存在！')
  }
  // 向客户端写入文件
  const buffer = fs.readFileSync(filePath)
  return ctx.body = buffer
}